package cn.springcloud.alibaba.auth.common.security.filter;

import cn.springcloud.alibaba.auth.common.security.TokenAuthentication;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理收到的token并为spring-security上下文生成及注入Authenticaion实例
 */
@Slf4j
public class AuthenticationTokenFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String token = this.resolveToken(request);
		if (StringUtils.isNotBlank(token)) {
			TokenAuthentication authentication = new TokenAuthentication(token);
			SecurityContextHolder.getContext().setAuthentication(authentication);
			System.out.println("Set authentication with non-empty token");
		}
		filterChain.doFilter(request, response);
	}

	private String resolveToken(HttpServletRequest request) {
		String token = request.getHeader("SAAS-TOKEN");
		if (StringUtils.isBlank(token)) {
			token = request.getParameter("SAAS-TOKEN");
		}
		return token;
	}
}
